
import wx
import os
import sqlite3
import ConfigParser
import string
import wx.lib.filebrowsebutton as filebrowsebutton




Config = ConfigParser.ConfigParser()
Config.read("config.ini")

DSF = Config.get('SETTINGS','dsf')
SSF = Config.get('SETTINGS','ssf')
XBMCDIR = Config.get('SETTINGS','xbmcdir')
FANARTPATH = Config.get('SETTINGS','FANARTPATH')
THUMBSPATH = Config.get('SETTINGS','THUMBSPATH')
SQLDIR = Config.get('SETTINGS','sqldir') #For Sqlite3
DBUSER = Config.get('SETTINGS','dbuser') #For MySQL
DBPASS = Config.get('SETTINGS','dbpass') #For MySQL
DBTYPE = Config.get('SETTINGS','dbtype') #Sqlite or MySql
DBIP = Config.get('SETTINGS','dbip')    #For MySQL
DBNAME = Config.get('SETTINGS','dbname') #For MySQL
PORT = Config.get('SETTINGS','port')# For Python MySQL
CHARSET = 'utf8'
UNICODE = True
WARNINGS = True
CONNTYPE ='Sqlite' #Default db connector
DEFAULTDIR = '.'
if DBTYPE == '':
    DBTYPE == 'Sqlite3'
if DBTYPE == 'MySql':

    try:
        import MySQLdb
        CONNTYPE = 'MySQLdb'
#   python mysql client
    except:
        import mysql.connector as MySQLpy
        CONNTYPE = 'MySQLpy'
        connstring = {
              'host': DBIP,
              'port': PORT,
              'database': DBNAME,
              'user': DBUSER,
              'password': DBPASS,
              'charset': CHARSET,
              'use_unicode':UNICODE,
              'get_warnings':WARNINGS,
              }


   

    def OnButton1Button(self,event):
        #self.getDir =  self.DirCtrl1.GetPath()
        #return getDir
        self.Close()


def create(parent):
    return ConfigWindow(parent)

[wxID_SQL, wxID_EXITBUTTON1, wxID_SAVEBUTTON2, wxID_SQLBUTTON3,
 wxID_SQLDESTBTN,  wxID_SQLFANARTBTN,
 wxID_SQLSQLBTN,wxID_FRAME1STATICTEXT1,
 wxID_SQLSQLTYPECB, wxID_SQLSRCBTN,wxID_SQLSQLTXT,
 wxID_SQLTEXTCTRL6, wxID_SQLTEXTCTRL7, wxID_SQLTHUMBSBTN,
 wxID_SQLTHUMBSTXT, wxID_SQLXBMCBTN, 
 ] = [wx.NewId() for _init_ctrls in range(16)]

class ConfigWindow(wx.Dialog):
    def _init_ctrls(self, prnt):

        wx.Dialog.__init__(self, id=wxID_SQL, name=u'id_SQL', parent=prnt,
              pos=wx.Point(470, 247), size=wx.Size(1080, 653),
              style=wx.DEFAULT_DIALOG_STYLE, title='Configuration Settings')
        self.SetClientSize(wx.Size(1080, 653))
        self.staticText1 = wx.StaticText(id=wxID_FRAME1STATICTEXT1,
              label=u'Changes require restart of application', name='staticText1', parent=self,
              pos=wx.Point(159, 25), size=wx.Size(650, 35), style=0)
       
        self.xbmcbtn = wx.lib.filebrowsebutton.DirBrowseButton(buttonText='XBMC',
              dialogTitle='', id=wxID_SQLXBMCBTN,
              labelText="", newDirectory=False,
              parent=self, pos=wx.Point(10,80), size=wx.Size(800, 48),
              startDirectory=XBMCDIR, style=wx.TAB_TRAVERSAL,
              toolTip="XBMC Folder Location - normally /user/.xbmc")
        self.xbmcbtn.SetWindowVariant(wx.WINDOW_VARIANT_SMALL)
               
        self.thumbsbtn = wx.lib.filebrowsebutton.DirBrowseButton(buttonText='Thumbs',
              dialogTitle='', id=wxID_SQLTHUMBSBTN,
              labelText="", newDirectory=False,
              parent=self, pos=wx.Point(10,160), size=wx.Size(800, 48),
              startDirectory=THUMBSPATH, style=wx.TAB_TRAVERSAL,
              toolTip="Thumnail Folder Location - normally userdata/Thumbnails/Video/")
        
        
        self.fanartbtn = wx.lib.filebrowsebutton.DirBrowseButton(buttonText='Fanart',
              dialogTitle='', id=wxID_SQLFANARTBTN,
              labelText="", newDirectory=False,
              parent=self, pos=wx.Point(10,240), size=wx.Size(800, 48),
              startDirectory=FANARTPATH, style=wx.TAB_TRAVERSAL,
              toolTip="Fanart Folder Location - normally userdata/Thumbnails/Video/Fanart")
        
              
        
        self.srcbtn = wx.lib.filebrowsebutton.DirBrowseButton(buttonText='SrcDir',
              dialogTitle='', id=wxID_SQLSRCBTN,
              labelText="", newDirectory=False,
              parent=self, pos=wx.Point(10,320), size=wx.Size(800, 48),
              startDirectory=SSF, style=wx.TAB_TRAVERSAL,
              toolTip="Startup Folder for Source Window")
           

        self.destbtn = wx.lib.filebrowsebutton.DirBrowseButton(buttonText='DestDir',
              dialogTitle='', id=wxID_SQLDESTBTN,
              labelText="", newDirectory=False,
              parent=self, pos=wx.Point(10,400), size=wx.Size(800, 48),
              startDirectory=DSF, style=wx.TAB_TRAVERSAL,
              toolTip="Startup Folder for Destination Window")
        self.sqldirbtn = wx.lib.filebrowsebutton.FileBrowseButton(buttonText='SqlDB',
              dialogTitle='', id=wxID_SQLSQLBTN,
              labelText="", parent=self, pos=wx.Point(10,480), size=wx.Size(800, 48),
              startDirectory=SQLDIR, style=wx.TAB_TRAVERSAL,
              toolTip="Sqlite3 Location - normally userdata/Database/MyVideos34.db")
           

        self.sqltypecb = wx.ComboBox(choices=["Sqlite3","MySql"], id=wxID_SQLSQLTYPECB,
              name=u'sqltypecb', parent=self, pos=wx.Point(860, 200),
              size=wx.Size(200, 45), style=0, value=DBTYPE)
        self.sqltypecb.SetLabel(u'Sql Type')
        self.sqltypecb.Bind(wx.EVT_COMBOBOX, self.OnSqltypecbCombobox,
              id=wxID_SQLSQLTYPECB)


        self.dbpwtxt = wx.TextCtrl(id=wxID_SQLTEXTCTRL6, name='DBPASS',
              parent=self, pos=wx.Point(830, 350), size=wx.Size(240, 50),
              style=0, value=DBPASS)

        self.dbusertxt = wx.TextCtrl(id=wxID_SQLTEXTCTRL7, name='dbuser',
              parent=self, pos=wx.Point(830, 280), size=wx.Size(240, 50),
              style=0, value=DBUSER)
        self.dbusertxt.SetToolTip(wx.ToolTip("MYSQL Username from advancedsettings.xml"))

        self.dbnametxt = wx.TextCtrl(id=wxID_SQLSQLTXT, name=u'dbname',
              parent=self, pos=wx.Point(830, 420), size=wx.Size(240, 50),
              style=0, value=DBNAME)
        self.dbnametxt.SetToolTip(wx.ToolTip("MySQL DB Name from advancedsettings.xml"))

        self.dbiptxt = wx.TextCtrl(id=wxID_SQLSQLTXT, name=u'dbip',
              parent=self, pos=wx.Point(830, 490), size=wx.Size(240, 50),
              style=0, value=DBIP)
        self.dbiptxt.SetToolTip(wx.ToolTip("MySQL DB IP# from advancedsettings.xml"))


        self.dbpwtxt.SetToolTip(wx.ToolTip("MySQL Password from advancedsettings.xml"))

       
        self.button1 = wx.Button(id=wxID_EXITBUTTON1, label=u'Exit',
              name='button1', parent=self, pos=wx.Point(620, 585),
              size=wx.Size(150, 50), style=0)
        self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
              id=wxID_EXITBUTTON1)

        self.button2 = wx.Button(id=wxID_SAVEBUTTON2, label=u'Save',
              name='button2', parent=self, pos=wx.Point(800, 585),
              size=wx.Size(217, 50), style=0)
        self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
              id=wxID_SAVEBUTTON2)

        self.button3 = wx.Button(id=wxID_SQLBUTTON3, label='Load Defaults',
              name='button3', parent=self, pos=wx.Point(820, 112),
              size=wx.Size(240, 50), style=0)
        self.button3.Bind(wx.EVT_BUTTON, self.OnButton3Button,
              id=wxID_SQLBUTTON3)

       
    def __init__(self, parent):
        self._init_ctrls(parent)
        self.sqldirbtn.SetValue(SQLDIR)
        self.destbtn.SetValue(DSF)
        self.srcbtn.SetValue(SSF)
        self.fanartbtn.SetValue(FANARTPATH)
        self.xbmcbtn.SetValue(XBMCDIR)
        self.thumbsbtn.SetValue(THUMBSPATH)
        if self.sqltypecb.GetValue() == 'Sqlite3':
            self.dbusertxt.Show(False)
            self.dbpwtxt.Show(False)
            self.dbnametxt.Show(False)
            self.dbiptxt.Show(False)
            self.sqldirbtn.Show(True)
        if self.sqltypecb.GetValue() == 'MySql':
            self.dbusertxt.Show(True)
            self.dbpwtxt.Show(True)
            self.dbnametxt.Show(True)
            self.dbiptxt.Show(True)
           
            self.sqldirbtn.Show(False)


    def OnSqltypecbCombobox(self, event):
        if self.sqltypecb.GetValue() == 'Sqlite3':
            self.dbusertxt.Show(False)
            self.dbpwtxt.Show(False)
            self.dbnametxt.Show(False)
            self.dbiptxt.Show(False)
            #self.sqldirbt.Show(True)
            self.sqldirbtn.Show(True)
            CONNTYPE ='Sqlite3'
        if self.sqltypecb.GetValue() == 'MySql':
            self.dbusertxt.Show(True)
            self.dbpwtxt.Show(True)
            self.dbnametxt.Show(True)
            self.dbiptxt.Show(True)
            #self.sqldirtxt.Show(False)
            self.sqldirbtn.Show(False)
            try:
                import MySQLdb
                CONNTYPE = 'MySQLdb'
        #     python mysql client
            except:
                import mysql.connector as MySQLpy
                CONNTYPE = 'MySQLpy'
                connstring = {
                   'host': DBIP,
                   'port': PORT,
                   'database': DBNAME,
                   'user': DBUSER,
                   'password': DBPASS,
                   'charset': CHARSET,
                   'use_unicode':UNICODE,
                   'get_warnings':WARNINGS,
                   }

   
        

        



    def OnThumbsbtnButton(self, event):
        
        thumbsdir = self.thumbsbtn.GetValue()
        
    def OnFanartbtnButton(self, event):
        
        fanartdir = self.fanartbtn.GetValue()
       


   

    def OnButton1Button(self, event):
        self.Destroy()
        self.Close()

    def OnButton2Button(self, event):
        #Save Settings

        DSF = self.destbtn.GetValue()
        SSF = self.srcbtn.GetValue()
        XBMCDIR = self.xbmcbtn.GetValue()
        if not os.path.isdir(XBMCDIR):
            wx.MessageBox("XBMC Dir not found!")
            return
        FANARTPATH =self.fanartbtn.GetValue()
        if not os.path.isdir(FANARTPATH):
            wx.MessageBox("Fanart Path not found!")
            return
        THUMBSPATH = self.thumbsbtn.GetValue()
        if not os.path.isdir(THUMBSPATH):
            wx.MessageBox("Thumbs Path not found!")
            return
        SQLDIR = self.sqldirbtn.GetValue()
        DBTYPE = self.sqltypecb.GetValue()
        if DBTYPE == 'Sqlite3':
            if not os.path.isfile(SQLDIR):
                wx.MessageBox("Video Database not found!")
                return
            try:
                conn = sqlite3.connect(SQLDIR)
            except:
                wx.MessageBox("Error connecting to Sqlit3")
                conn.close
                return

        DBPASS = self.dbpwtxt.GetValue()
        DBUSER = self.dbusertxt.GetValue()
        DBNAME = self.dbnametxt.GetValue()
        DBIP   = self.dbiptxt.GetValue()
        if DBTYPE == 'MySql':
            try:
                import MySQLdb
                conn = MySQLdb.connect(DBIP,DBUSER,DBPASS,DBNAME)
            except:
                try:
                    import mysql.connector as MySQLpy
                    CONNTYPE = 'MySQLpy'
                    connstring = {
                       'host': DBIP,
                       'port': PORT,
                       'database': DBNAME,
                       'user': DBUSER,
                       'password': DBPASS,
                       'charset': CHARSET,
                       'use_unicode':UNICODE,
                       'get_warnings':WARNINGS,
                       }

                    conn = MySQLpy.connect(**connstring)
                except:
                    wx.MessageBox("MySql Err: Check User,Pass,Path,DBName")
                    #conn.close
                    return
            cursor = conn.cursor()
            sql = "select max(idPath) from path"
            cursor.execute(sql)
            try:
                strContent = cursor.fetchone()
            except:
                wx.MessageBox("Error connecting to MySQL")
                #conn.close
                return
        wx.MessageBox("Database Connection Established!")
        conn.close
        Config.set('SETTINGS','dsf',DSF)
        Config.set('SETTINGS','ssf',SSF)
        Config.set('SETTINGS','xbmcdir',XBMCDIR)
        Config.set('SETTINGS','fanartpath',FANARTPATH)
        Config.set('SETTINGS','thumbspath',THUMBSPATH)
        Config.set('SETTINGS','sqldir',SQLDIR)
        Config.set('SETTINGS','dbuser',DBUSER)
        Config.set('SETTINGS','dbpass',DBPASS)
        Config.set('SETTINGS','dbtype',DBTYPE)
        Config.set('SETTINGS','dbip',DBIP)
        Config.set('SETTINGS','dbname',DBNAME)
        Config.write(open(r'config.ini', 'w'))
        wx.MessageBox('Changes were saved!')
        return

    def OnButton3Button(self, event):
        #load default settings for operating system
        if os.name =='posix':
            settings = 'DEFLINUX'
            user = os.getenv("USER")
        if os.name == 'nt':
            user = os.getenv("USERNAME")
             #settings = 'DEFVISTA'
             #if NT
            settings = 'DEFWINXP'
        #if os.name == 'mac'
        Config.read("config.ini")
        DBTYPE = Config.get(settings,'DBTYPE')
        DSF = Config.get(settings,'DSF')
        SSF = Config.get(settings,'SSF')
        XBMCDIR = Config.get(settings,'XBMCDIR')
        XBMCDIR = XBMCDIR.replace('userid',user,1)
        FANARTPATH = Config.get(settings,'FANARTPATH')
        FANARTPATH = FANARTPATH.replace('userid',user,1)
        THUMBSPATH = Config.get(settings,'THUMBSPATH')
        THUMBSPATH = THUMBSPATH.replace('userid',user,1)
        SQLDIR = Config.get(settings,'SQLDIR')
        SQLDIR = SQLDIR.replace('userid',user,1)
        DBUSER = Config.get(settings,'DBUSER')
        DBPASS = Config.get(settings,'DBPASS')
        DBIP   = Config.get(settings,'dbip')
        DBNAME = Config.get(settings,'dbname')

        self.srcbtn.SetValue(SSF)
        self.destbtn.SetValue(DSF)
        self.xbmcbtn.SetValue(XBMCDIR)
        self.fanartbtn.SetValue(FANARTPATH)
        self.thumbsbtn.SetValue(THUMBSPATH)
        self.sqldirbtn.SetValue(SQLDIR)
        self.sqltypecb.SetValue(DBTYPE)
        self.dbpwtxt.SetValue(DBPASS)
        self.dbusertxt.SetValue(DBUSER)
        self.dbnametxt.SetValue(DBNAME)
        self.dbiptxt.SetValue(DBIP)
